/*
 *  Copyright (C) 2010 Martin Haulrich <mwh.isv@cbs.dk>
 *
 *  This file is part of the MatrixParser package.
 *
 *  The MatrixParser program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.osdtsystem.matrixparser.features;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.osdtsystem.matrixparser.logging.DebugData;
import org.osdtsystem.matrixparser.logging.Log;
import org.osdtsystem.matrixparser.main.MstTester;

/**
 *
 * @author Martin Haulrich
 */
public class SparseFeatureVector extends AbstractFeatureVector {
    Map<Feature, Double> features;
    final boolean enforceBinary;
    final boolean enforceBinaryWarn;

    public SparseFeatureVector() {
        this(false);
    }

    public SparseFeatureVector(boolean enforceBinary) {
        this.enforceBinary = enforceBinary;
        this.enforceBinaryWarn = true;
        features = new HashMap<Feature, Double>();
    }

    public double getValue(Feature f) {
        Double v = features.get(f);
        if (v == null) {
            return 0d;
        }
        return v;
    }

    void throwOrWarn(RuntimeException ex) {
        if (enforceBinaryWarn)
            Log.severe(ex.toString());
        else
            throw ex;
    }

/**
 * Feature with id zero is 'unknown feature' do not add this
 * @param f
 * @param v
 */
    public void addValue(Feature f, double v) {
        double newvalue = v + getValue(f);
        if (enforceBinary && ! (Double.compare(newvalue, 0) == 0 || Double.compare(newvalue, 1) == 0))
            throwOrWarn(new IllegalStateException("Setting feature " + f
                    + " to non-binary value " + newvalue + " by adding amount "
                    + v + " in binary feature vector"));
        if (f.id() > 0) {
            features.put(f, newvalue);
        }// else {
        //    features.put(f, v == 0 ? 0d : 1d);
        //}
    }

    public void addValue(FeatureHandler fh, CharSequence chars, double v) {
        Feature f = fh.getFeature(chars.toString());
        double newvalue = v + getValue(f);
        if (enforceBinary && ! (Double.compare(newvalue, 0) == 0 || Double.compare(newvalue, 1) == 0))
            throwOrWarn(new IllegalStateException("Setting feature " + f + "(" + chars + ")"
                    + " to non-binary value " + newvalue + " by adding amount "
                    + v + " in binary feature vector"));
        if (f.id() > 0) {
            features.put(f, newvalue);
        }// else {
    }

    public void setValue(Feature f, double v) {
        if (enforceBinary && ! (Double.compare(v, 0) == 0 || Double.compare(v, 1) == 0))
            throwOrWarn(new IllegalStateException("Setting feature " + f
                        + " to non-binary value " + v + " in binary feature vector"));
        if (f.id() > 0) {
            features.put(f, v);
        }// else {
        //    features.put(f, v == 0 ? 0d : 1d);
        //}
    }

    Feature[] keys() {
        Feature[] keys = features.keySet().toArray(new Feature[0]);
        Arrays.sort(keys);
        return keys;
    }

    public int checksum() {
        int checksum = 13;
        for (Feature key : keys()) {
            float f = features.get(key).floatValue();
            int valueAsInt = Float.floatToIntBits(f) ^ 0xf;
            checksum = (19 * checksum + valueAsInt) * 23 + key.id();
        }
        return checksum;
    }

    public String checksum64() {
        return Log.base64(checksum());
    }

    String _debugNonBinaryFeatures() {
        StringBuilder sb = new StringBuilder().append("SparseFeatureVector: checksum=").append(checksum64()).append(" ");
        MapTwoWayFeatureHandler featureHandler 
                = (MapTwoWayFeatureHandler) DebugData.model.featureHandler();
        sb.append("Non-binary features:\n");
        for (Feature key: keys()) {
            double value = getValue(key);
            if (Double.compare(value, 0) != 0 && Double.compare(value, 1) != 0) {
                sb.append(key).append("(").append(featureHandler.getName(key)).append("): ")
                        .append(value).append("\n");
            }
        }
        sb.append("\n");
        return sb.toString();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder().append("SparseFeatureVector: checksum=").append(checksum64()).append(" ");
        sb.append(_debugNonBinaryFeatures());
        String sep = "";
        int count = 0;
        for (Feature key : keys()) {
            if (count++ % 20 == 0)
                sb.append("\n\t");
            sb.append(sep).append(String.format("%.2g", features.get(key)));
            sep = " ";
            if (count > 100) {
                sb.append("\n\t...");
                break;
            }
        }
        sb.append("\n");
        return sb.toString();
    }


    @Override
    public boolean equals(Object obj) {
        if (! (obj instanceof FeatureVector))
            return false;
        FeatureVector other = (FeatureVector) obj;
        for (Entry<Feature,Double> entry : features.entrySet()) {
            if (Double.compare(other.getValue(entry.getKey()),
                    entry.getValue()) != 0) {
                return false;
            }
        }

        for (Entry<Feature,Double> entry : other) {
            if (Double.compare(getValue(entry.getKey()),
                    entry.getValue()) != 0) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + (this.features != null ? this.features.hashCode() : 0);
        return hash;
    }

    public int size() {
        return features.size();
    }

    @Override
    public Iterator<Entry<Feature, Double>> iterator() {
        return features.entrySet().iterator();
    }

    public void ignoreFeatures(FeatureVector fv) {
        for (Entry<Feature,Double> entry : this) {
            Feature key = entry.getKey();
            if (Double.compare(fv.getValue(key), 0) != 0)
                setValue(key, 0);
        }
    }

    public void add(FeatureVector fv) {
        for (Entry<Feature,Double> entry : fv) {
            if (Double.compare(entry.getValue(), 0) != 0)
                addValue(entry.getKey(), entry.getValue());
        }
    }

}
